//
//  DetailViewController.m
//  DaDaBao
//
//  Created by admin on 15/8/14.
//  Copyright (c) 2015年 User. All rights reserved.
//
#import "SecureViewController.h"
#import "DetailViewController.h"
#import "CalculatorControl.h"
#import "ProjectDetailHeaderView.h"
#import "MoreDetailViewController.h"
#import "ProjectDetailModel.h"
#import "InvestmentViewController.h"

@interface DetailViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>

@property(nonatomic,strong)TopView *topView;
@property(nonatomic,strong)UITableView *detailTable;
@property(nonatomic,strong)NSMutableArray *tableArray;
@property(nonatomic,strong)UIButton *investBtn;//投资按钮
@property(nonatomic,strong)UIButton *calculatorBtn;//计算器按钮
@property(nonatomic,strong)NSString *projectID;
@property(nonatomic,assign)float cellHeight;

@property(nonatomic,strong) UIButton *noDataBt;
@property(nonatomic,strong)UIButton *tipBt;

@property(nonatomic,strong)ProjectDetailModel *projectDetailModel;

@property(nonatomic,strong)ProjectDetailHeaderView *tableHeaderView;

@end

@implementation DetailViewController

//产品是否在有效的销售中
- (BOOL)isValidButton
{
    if ([_projectDetailModel.dueStatus intValue]!=0)
    {
        
        if([_projectDetailModel.saleStatus intValue]!=2)
            
        {
            if([_projectDetailModel.leftCredit intValue] !=0)
            {
                return TRUE;
            }
            else
            {
                return FALSE;
            }
        }
        else
        {
            return FALSE;
        }
    }
    else
    {
        return FALSE;
    }
}

- (id)initWithProjectID:(NSString *)projectID
{
    self = [super init];
    if(self)
    {
        _projectID = projectID;
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.topView];
    [self.view addSubview:self.tipBt];
    [self.view addSubview:self.noDataBt];
    [self getData];

}
-(void)getData
{
    NSDictionary *dict = @{ @"productId" : _projectID };
    [MBProgressHUD showHUDAddedTo:self.view animated:TRUE];
    _noDataBt.hidden = TRUE;
    _tipBt.hidden = TRUE;
    
    [AppGlobalClass PostDataWithNSstring:PROJECT_DETAIL_URL withDictionary:dict success:^(NSDictionary *dictionary){
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            _projectDetailModel = [[ProjectDetailModel alloc]initWithDictionary:[[[[dictionary objectForKey:@"responseData"]firstObject] objectForKey:@"rows"] firstObject]];
            [self.view addSubview:self.detailTable];
            [self.view addSubview:self.investBtn];
            [self.investBtn addSubview:self.calculatorBtn];
            
        }
        else
        {
            ALERT_VIEW([dictionary objectForKey:@"message"]);
        }
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } failure:^(NSError *error){
        _noDataBt.hidden = FALSE;
        _tipBt.hidden = TRUE;

        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    } networkerror:^(NSString *networkerror){
        _noDataBt.hidden = TRUE;
        _tipBt.hidden = FALSE;
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:TRUE];
    }];

}
#pragma mark--CreateUI

//没网提示
-(UIButton *)tipBt
{
    if (!_tipBt) {
        _tipBt = [[UIButton alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_tipBt setBackgroundImage:[UIImage imageNamed:@"network_error"] forState:UIControlStateNormal];
        [_tipBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        _tipBt.hidden = TRUE;
    }
    return _tipBt;
}

- (UIButton *)noDataBt
{
    if (!_noDataBt) {
        _noDataBt = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_WIDTH - 116.0f) / 2.0f, (SCREEN_HEIGHT - 130.0f) / 2.0f, 116.0f, 130.0f)];
        [_noDataBt addTarget:self action:@selector(buttonAgainTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_noDataBt setImage:[UIImage imageNamed:@"img_nodata"] forState:UIControlStateNormal];
        _noDataBt.hidden = TRUE;
    }
    return _noDataBt;
}


-(NSMutableArray *)tableArray
{
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] initWithArray:@[@[@"项目名称",@"项目类型",@"起投金额",@"还款方式"],@[@"更多详情"]]];
    }
    return _tableArray;
}

//navgationBar
-(TopView *)topView
{
    if (!_topView) {
        _topView = [[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_HEIGHT, 64.0f)];
        _topView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
        [_topView setTitile:@"详情"];
        
        UIButton *backBtn = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, 20.0f, 64.0f, 44.0f)];

        [backBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
        [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_topView addSubview:backBtn];
        
    }
    return _topView;
}


//表头
- (ProjectDetailHeaderView *)tableHeaderView
{
    if (!_tableHeaderView) {
        _tableHeaderView = [[ProjectDetailHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 228.0f) andModel:_projectDetailModel];
        _tableHeaderView.backgroundColor = [UIColor whiteColor];
    }
    return _tableHeaderView;
}

//创建表
- (UITableView *)detailTable
{
    if (!_detailTable) {
        CGFloat tableOriginY = self.topView.frame.origin.y+self.topView.frame.size.height;
        _detailTable = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, tableOriginY, SCREEN_WIDTH, SCREEN_HEIGHT-tableOriginY-self.investBtn.frame.size.height) style:UITableViewStyleGrouped];
        _detailTable.showsVerticalScrollIndicator = NO;
        _detailTable.delegate = self;
        _detailTable.dataSource = self;
        _detailTable.rowHeight = 50.0f;
        _detailTable.tableHeaderView = self.tableHeaderView;
        _detailTable.backgroundColor = [UIColor hexStringToColor:@"#ebebeb"];
    }
    return _detailTable;
}

//立即投资按钮
- (UIButton *)investBtn
{
    if (!_investBtn) {
        _investBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _investBtn.frame = CGRectMake(0.0f, SCREEN_HEIGHT-50.0f, SCREEN_WIDTH, 50.0f);
        
        if([self isValidButton])
        {
            _investBtn.backgroundColor = [UIColor hexStringToColor:@"#242d3c"];
            [_investBtn addTarget:self action:@selector(buttonInvestTapped:) forControlEvents:UIControlEventTouchUpInside];
        }
        else
        {
            _investBtn.backgroundColor = [UIColor lightGrayColor];
        }
        [_investBtn setTitle:@"立即投资" forState:UIControlStateNormal];
        [_investBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    return _investBtn;
}
//计算器按钮
- (UIButton *)calculatorBtn
{
    if (!_calculatorBtn) {
        _calculatorBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _calculatorBtn.frame = CGRectMake(20.0f, 10.0f, 30, 30.0f);
        
        if([self isValidButton])
        {
            [_calculatorBtn addTarget:self action:@selector(buttonCalculatorTapped:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        [_calculatorBtn setBackgroundImage:[UIImage imageNamed:@"co"] forState:UIControlStateNormal];
        [_calculatorBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
      }
    return _calculatorBtn;
}
#pragma mark-返回上一页
-(void)buttonBackTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:TRUE];
}
#pragma mark-再次请求
- (void)buttonAgainTapped:(id)sender
{
    [self getData];
}
#pragma mark--计算器方法
- (void)buttonCalculatorTapped:(id)sender
{
    
    //    计算器
    CalculatorControl *control = [[CalculatorControl alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, SCREEN_HEIGHT)];
    control.alpha=0.0f;
    [control countMoneyWithRate:_projectDetailModel.expectedReturnRatio andTime:_projectDetailModel.timeLimit];
    [self.view addSubview:control];
    [UIView beginAnimations:nil context:nil];
    //设置动画持续时间
    [UIView setAnimationDuration:0.8];
    control.alpha = 1.0f;
       //提交动画
    [UIView commitAnimations];
}

#pragma mark--投资方法
- (void)buttonInvestTapped:(id)sender
{
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"token"] == nil)
    {
        LoginViewController *loginViewCon = [[LoginViewController alloc]init];
        [self presentViewController:loginViewCon animated:TRUE completion:^{}];
    }
    else
    {
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"idCardVStatus"] isEqualToNumber:[NSNumber numberWithInt:0]])
        {
       
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您尚未进行实名认证，是否进行实名认证？" delegate:self cancelButtonTitle:@"不，谢谢" otherButtonTitles:@"立刻认证", nil];
            alert.tag = 10000;
            [alert show];
        }else
        {
            InvestmentViewController *investVC = [[InvestmentViewController alloc] initWithProductId:_projectDetailModel.productId];
            [self.navigationController pushViewController:investVC animated:TRUE];
        }
    }
}

#pragma mark--UITableViewDelegate&DataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.textLabel.font = [UIFont systemFontOfSize:14.0f];
        cell.detailTextLabel.font = [UIFont systemFontOfSize:14.0f];

        UILabel *productName = [[UILabel alloc] initWithFrame:CGRectMake(80.0f, 10.0f, SCREEN_WIDTH-90.0f, 20.0f)];
        productName.tag = 1000;
        productName.font = [UIFont systemFontOfSize:14.0f];
        productName.textAlignment = NSTextAlignmentRight;
        productName.numberOfLines = 0;
        productName.textColor = [UIColor grayColor];
        [cell addSubview:productName];
        
        if (indexPath.section == 1) {
            UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 50.0f)];
            textLabel.font = [UIFont systemFontOfSize:14.0f];
            textLabel.textAlignment = NSTextAlignmentCenter;
            textLabel.tag = 100;
            [cell.contentView addSubview:textLabel];
        }
    }
    NSArray *array = self.tableArray[indexPath.section];
    if (indexPath.section == 0) {
        cell.textLabel.text = array[indexPath.row];
        
        if(indexPath.row == 0)
        {
            float height =[UILabel height:_projectDetailModel.productName widthOfFatherView:SCREEN_WIDTH-90.0f textFont:[UIFont systemFontOfSize:14.0f]]+0.1f;

            _cellHeight = height+24.0f;
            UILabel *productName = (UILabel *)[cell viewWithTag:1000];
            productName.text = _projectDetailModel.productName;
            productName.frame = CGRectMake(80.0f, 12.0f, SCREEN_WIDTH-90.0f, height+12.0f);
            [cell addSubview:productName];
        }
        if(indexPath.row == 1)
        {
            cell.detailTextLabel.text = _projectDetailModel.productType;
        }
        if(indexPath.row == 2)
        {
            if([_projectDetailModel.inceptMoney doubleValue] > 9999)
            {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2lf万",[_projectDetailModel.inceptMoney doubleValue] /10000.0f];
            }
            else
            {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f元",[_projectDetailModel.inceptMoney doubleValue]];
            }
        }
        if(indexPath.row == 3)
        {
            cell.detailTextLabel.text = _projectDetailModel.repaymentMethod;
        }
    }else
    {
        UILabel *textLabel = (UILabel *)[cell.contentView viewWithTag:100];
        textLabel.text = array[indexPath.row];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section==1) {
        if (indexPath.row==0) {
            MoreDetailViewController *moreVC = [[MoreDetailViewController alloc] initWithProductID:_projectDetailModel.productId andProductName:_projectDetailModel.productName];
            [self.navigationController pushViewController:moreVC animated:TRUE];
        }
       
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.tableArray.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray *array = self.tableArray[section];
    return array.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 7.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section==0)
    {
        if (indexPath.row==0 && _cellHeight>44.0f)
        {
            return _cellHeight;
        }
        else{
            return 50.0f;
        }
        
    }
    else{
        return 50.0f;
    }
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 10000)
    {
        if (buttonIndex == 1)
        {
            SecureViewController * vc = [[SecureViewController alloc]init];
            [self.navigationController pushViewController:vc animated:TRUE];
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
